/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.service;

import br.com.foxline.model.Corrector;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author roniere
 */
@Stateless
public class CorrectorService extends GenericService<Corrector> {

    public CorrectorService() {
        super(Corrector.class);
    }

    public List<Corrector> findCorrector(Corrector corrector) {
        List<Corrector> correctors = new ArrayList<Corrector>();

        String sql = "SELECT c FROM Corrector c WHERE ";
        System.out.print("passou");
        if ((corrector.getName() != null) && (!corrector.getName().equals(""))) {
            sql += " lower(c.name) like lower(:name) and  ";
        }

        if ((corrector.getCreci() != null) && (!corrector.getCreci().equals(""))) {
            sql += " lower(c.creci) like lower(:creci) and  ";
        }

        if ((corrector.getCpf() != null) && (!corrector.getCpf().equals(""))) {
            sql += " lower(c.cpf) like lower(:cpf) and  ";
        }

        sql += "  c.active=TRUE";

        Query query = getEntityManager().createQuery(sql);

        if ((corrector.getName() != null) && (!corrector.getName().equals(""))) {
            query.setParameter("name", "%" + corrector.getName() + "%");
        }
        if ((corrector.getCreci() != null) && (!corrector.getCreci().equals(""))) {
            query.setParameter("creci", "%" + corrector.getCreci() + "%");
        }
        if ((corrector.getCpf() != null) && (!corrector.getCpf().equals(""))) {
            query.setParameter("cpf", "%" + corrector.getCpf() + "%");
        }
        correctors = query.getResultList();
        return correctors;
    }

    public Corrector findCorrectorByUser(String userName) {
        String sql = "SELECT c FROM Corrector c JOIN c.user u WHERE u.login = :name";

        Query query = getEntityManager().createQuery(sql);
        query.setParameter("name", userName);

        Corrector c = (Corrector) query.getSingleResult();
        return c;
    }

    public List<Corrector> autocomplete(String name) {
        List<Corrector> lista = new ArrayList<Corrector>();
        String sql = "Select c from Corrector c where lower(c.name) like lower(:name)";
        Query query = getEntityManager().createQuery(sql).setMaxResults(50);

        if (name != null) {
            query.setParameter("name", "" + name + "%");
        }

        lista = query.getResultList();
        return lista;
    }
}
